package socketServer

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"net"
)

type Pack struct {
	Addr *net.UDPAddr
	Data []byte
}

func CreateServer(srvAddr string, writerBuffer, readerBuffer int) error {
	// 创建UDP监听地址（本地地址）
	conn, err := createServer(srvAddr, writerBuffer, readerBuffer)
	if err != nil {
		if conn != nil {
			conn.Close()
		}

		return err
	}

	// 创建监听线程
	go handleRead(readerBuffer)

	// 保存变量
	serverAddr = srvAddr
	connect = conn

	return nil
}

func createServer(srvAddr string, writerBuffer, readerBuffer int) (*net.UDPConn, error) {
	// 创建UDP监听地址（本地地址）
	localAddr, err := net.ResolveUDPAddr("udp", srvAddr)
	if err != nil {
		return nil, err
	}

	// 创建UDP连接
	conn, err := net.ListenUDP("udp", localAddr)
	if err != nil {
		return nil, err
	}

	// 设置操作系统的socket缓存
	err = conn.SetReadBuffer(readerBuffer)
	if err != nil {
		return nil, err
	}
	err = conn.SetWriteBuffer(writerBuffer)
	if err != nil {
		return nil, err
	}

	return conn, nil
}

func Send(remoteAddress string, data []byte) error {
	remoteAddr, err := net.ResolveUDPAddr("udp", remoteAddress)
	if err != nil {
		return err
	}

	_, err = connect.WriteToUDP(data, remoteAddr)
	if err != nil {
		return err
	}

	return nil
}

func handleRead(readerBuffer int) {
	buffer := make([]byte, readerBuffer)
	for {
		// 等待数据到达
		cnt, addr, err := connect.ReadFromUDP(buffer)
		if err != nil {
			commLogger.Error("读取socket数据出错: " + err.Error())
			continue
		}

		// 通知数据到达
		Event.Notify(addr.String(), &Pack{
			Addr: addr,
			Data: buffer[:cnt],
		})
	}
}
